import os
import tkinter as tk
from tkinter import messagebox
from docx import Document
from win32com import client


def check_file_extension(extension):
    extension = extension.lower()
    if extension == '.pdf':
        return False
    if extension in ['.docx', '.doc']:
        return True
    if extension == '.txt':
        return True
    return False


def read_docx(file_path):
    doc = Document(file_path)
    return [para.text for para in doc.paragraphs]


def read_doc(file_path):
    word = client.Dispatch("Word.Application")
    doc = word.Documents.Open(file_path)
    doc_content = [para.Range.Text.strip() for para in doc.Paragraphs]
    doc.Close()
    word.Quit()
    return doc_content


def search_and_extract(file_path, output_file, line_patterns_with_lines):
    file_extension = os.path.splitext(file_path)[1].lower()
    if not check_file_extension(file_extension):
        messagebox.showwarning("Warning", "请输入正确文件格式!目前支持txt, doc, docx")
        return

    # 根据文件类型读取文件内容
    if file_extension == '.txt':
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
    elif file_extension == '.docx':
        lines = read_docx(file_path)
    elif file_extension == '.doc':
        lines = read_doc(file_path)

    with open(output_file, 'w', encoding='utf-8') as out_f:
        for line_number, line in enumerate(lines, start=1):
            stripped_line = line.strip()
            for pattern, num_lines in line_patterns_with_lines.items():
                if stripped_line.startswith(pattern):
                    print(f"Matched Pattern: {pattern}")
                    out_f.write(line + "\n")  # 写入匹配的行
                    if num_lines > 0:
                        for i in range(1, num_lines + 1):
                            if line_number + i < len(lines):  # 检查是否超出文件行数
                                out_f.write(lines[line_number + i] + "\n")
                    out_f.write("\n")
                    break


def start_search():
    # 获取用户输入的文件名
    file_name = file_path_var.get()
    if not file_name:
        messagebox.showwarning("Warning", "请输入文件名!")
        return

    # 构造文件的完整路径，假设脚本和文件位于同一个文件夹下
    file_path = os.path.join(os.getcwd(), file_name)

    # 检查文件是否存在
    if not os.path.isfile(file_path):
        messagebox.showwarning("Warning", "File not found. Please enter a valid file name.")
        return

    # 获取用户输入的行开头格式列表和行数
    line_start_input = line_start_var.get()
    if not line_start_input:
        messagebox.showwarning("Warning", "请输入行开头格式列表!")
        return

    # 将行开头格式列表转换为字典
    line_patterns_with_lines = {}
    for entry in line_start_input.split(";"):
        parts = entry.split(":")
        pattern = parts[0].strip()
        num_lines = int(parts[1].strip()) if len(parts) > 1 and parts[1].strip().isdigit() else 0
        line_patterns_with_lines[pattern] = num_lines

    output_filepath = "output.txt"  # 输出文件的名称

    search_and_extract(file_path, output_filepath, line_patterns_with_lines)
    messagebox.showinfo("Info", f"搜索完毕, 文件储存在 {output_filepath}.")


# 创建主窗口
root = tk.Tk()
root.title("Search and Extract")
root.geometry("600x400")

# 创建并显示文件路径输入框和按钮
file_path_var = tk.StringVar()
line_start_var = tk.StringVar()

label1 = tk.Label(root, text="输入文档的名字 + 文件后缀", font=("Arial", 14))
label1.pack(pady=10)

file_entry = tk.Entry(root, width=50, textvariable=file_path_var)
file_entry.pack(pady=5)

label2 = tk.Label(root, text="输入行开头格式列表（格式: pattern:lines; pattern:lines）", font=("Arial", 14))
label2.pack(pady=10)

line_start_entry = tk.Entry(root, width=50, textvariable=line_start_var)
line_start_entry.pack(pady=5)

start_button = tk.Button(root, text="开始", command=start_search, width=10, height=1)
start_button.pack(pady=20)

# text_setting = tk.Text(root, height=5, width=50, font=("Arial", 14))
# text_setting.pack(pady=10)

# 替换掉创建标签的部分
text_box = tk.Text(root, height=3, width=30, font=("Arial", 14), wrap=tk.WORD)
text_box.pack(pady=5)

# 将文本框设置为只读
text_box.config(state=tk.NORMAL)  # 允许修改
text_box.delete(1.0, tk.END)       # 清空文本框
text_box.insert(tk.END, "华为:import re:2;input_directory:1\n中兴\n阿尔米特")  # 插入固定文本
text_box.config(state=tk.DISABLED)  # 设置为只读

# 进入主循环
root.mainloop()
